import {createSlice} from "@reduxjs/toolkit";
import {getToken, removeToken, setToken} from "@/utils/storage";
import {getUserInfo, LoginApi} from "@/api/user";

const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setUserToken(state, action){
            state.token = action.payload
            setToken(action.payload)
        },
        setUserInfo(state, action){
            state.userInfo = action.payload
        },
        removeUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

const { setUserToken, setUserInfo, removeUserInfo } = userStore.actions

const LoginToken = (data) => {
    return async (dispatch) => {
        const res = await LoginApi(data)
        dispatch(setUserToken(res.data.token))
    }
}

const UserInfoApi = () => {
    return async (dispatch) => {
        const res = await getUserInfo()
        dispatch(setUserInfo(res.data))
    }
}

const userReducer = userStore.reducer

export { setUserToken, removeUserInfo, LoginToken, UserInfoApi }
export default userReducer